package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    //通过WeChatProperties获取配置文件里配置的属性
    @Autowired
    private WeChatProperties weChatProperties;

    //通过JwtProperties获取配置文件里的配置属性
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO userLogin(UserLoginDTO userLoginDTO) {
        //创建一个HashMap集合存放必要的四个参数
        HashMap<String, String> hashMap = new HashMap<>();
        //赋值必要参数
        hashMap.put("appid", weChatProperties.getAppid());
        hashMap.put("secret", weChatProperties.getSecret());
        hashMap.put("js_code", userLoginDTO.getCode());
        hashMap.put("grant_type", "authorization_code");
        //利用工具类创建httpClient获取get请求，并传入url与集合,获得带有openid的响应对象
        String response = HttpClientUtil.doGet(URL, hashMap);
        //获取字符串里的openid。这个是JSON格式字符串
        //先将字符串转换为JSON，然后获取（以前是data位置），这里叫openid
        JSONObject jsonObject = JSON.parseObject(response);
        //获取JSON的openid
        String openid = jsonObject.getString("openid");
        //判断openid是否为空或者null
        if (openid == null || openid.length() == 0)
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        //根据openid查询用户是否存在（openid是微信用户的唯一标识，也可以当做user数据库的id）
        User user = userMapper.getByOpenId(openid);
        //如果不存在创建用户，并主键返回user——id（先写不存在可少写冗余代码）
        if (user == null) {
            //创建用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //执行SQL创建用户，并主键返回user——id
            userMapper.insert(user);
        }
        //如果存在（不存在也创建好了）。设置JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        //封装VO返回
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();
        return userLoginVO;
    }
}
